var swf_url  = "/js/plupload/Moxie.swf";
var xap_url ="/js/plupload/Moxie.xap";

/***
var clickId     //上传按钮id
var fileName    //文件对应服务器（参数名字)
var url 		//上传地址
var maxFileSize //文件最大尺寸
var FileType    //文件类型
var progressBar //文件上传进度条DiV
var successType //文件处理类型判断，主要用于区分裁剪功能
var showImgDiv //文件上传后，显示在哪个DIV
var parameter //自定义参数数组
	 
***/	
function uploadFolderFile(fileName,url,clickId,maxFileSize,FileType,progressBar,successType,showImgDiv, parameter){
	var uploader = new plupload.Uploader({ 
		        runtimes : 'html5,flash,html4',
				browse_button : clickId, // you can pass in id...
		        url : url, 
				file_data_name:fileName,	//post  服务器文件名
		        unique_names : true,
				multi_selection: ( successType=='multi_img')?true:false , 		//判断多选图片 
		        
		        filters : {
		            max_file_size : maxFileSize,

					// Specify what files to browse for
		            mime_types: [
		                {title : " files", extensions : FileType}, //过滤文件类型
		            ]
		        },
				multipart_params: {"fid" : parameter[0],"id":parameter[1]},
				flash_swf_url : swf_url,
				silverlight_xap_url : xap_url, 
		 
		        // Post init events, bound after the internal events
		        init : {
		            UploadProgress: function(up, file) {
						if(up.runtime !='html4'){ 
							$(progressBar).parent('div').show();
							$(progressBar).css({'width':file.percent+'%'});//进度条  
							$('#zhengzai').show();
						}
		            },
		            FilesAdded: function(up, files) {	//选择文件后
		                // Called when files are added to queue
						uploader.start();
						if(up.runtime=='html4'){  
							$(progressBar).parent('div').css({'background':'#FFF'}).append("<div id='html4Progress' class='loading'></div><div id='html4ProgressFont' style='font-size:10px;color:red'>正在上传...</div>").show();//html4的进度条  
						}		
						if(successType == 'bussCard'){
                			$('.loading_gif').show();
						}	
		            },
					 FileUploaded: function(up, file, info) {	//单个文件上传完成后触发
						if(up.runtime=='html4'){ 
							$('#html4Progress','#html4ProgressFont').remove();  
						}
						var str = info.response;
						if(str != '' && str != null){
							var start = str.indexOf("{");
							var end = str.indexOf("}");
							if(start == -1 || end ==-1){
								showPluploadError(up,'',clickId,"上传失败",errorId)
							}else{
								var result ='';
								if(successType!="folderFile"){
									result = str.substr(start,end-start);
								} else {
									result = str;
								}
								var json =  eval("("+result+")");   
								if(json.status){ 
									showPluploadSuccess(file,json.uploadFile,successType,progressBar,showImgDiv,clickId,json); 
								}else{
									showPluploadError(up,'',clickId,json.msg,errorId);
								}
							}
						}else{
							showPluploadError(up,'',clickId,"上传失败",errorId)
						}
						
						$(progressBar).parent('div').hide();
						$('#zhengzai').hide();
						
				   },
				   Error: function(up, args) {
		                // Called when error occurs 
		                showPluploadError(up,'',clickId,args.message,errorId)
		            } 

		        }
		    });			
			//调用相机
			uploader.bind('init',function(){
				$('#camera').siblings('div').find('input').attr('accept','image/*').attr('capture','camera');
			});
			uploader.init();
} 

function showPluploadSuccess(file,msg,successType,progressBar,showImgDiv,clickId,json){ 
	    console.log(file)
		if (successType == 'cut01' || successType == 'cut02') {
			$("#target").attr("src", msg);
			var img = new Image();
			img.src = msg;
			img.onload = function() {
				var img_height = 0;
				var img_width = 0;
				var widthPersent = 0.0;
				var heightPersent = 0.0;
				var real_height = img.height;
				var real_width = img.width;
				if (real_height > 600) {
					heightPersent = real_height / 600.0;
				} 
				if (real_width > 800) {
					widthPersent = real_width / 800.0;
				}
				var arr = [ 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 7, 10, 13, 15, 17, 20 ];
				if (widthPersent == 0 && heightPersent == 0.0) {
					img_height = real_height;
					img_width = real_width;
					persent = 1;
				} else {
					if (widthPersent >= heightPersent) {
						for (var i = 0; i < arr.length; i++) {
							img_width = real_width / arr[i];
							if (img_width <= 800) {
								img_height = real_height / arr[i];
								persent = arr[i];
								break;
							}
						}
					}
					if (widthPersent < heightPersent) {
						for (var i = 0; i < arr.length; i++) {
							img_height = real_height / arr[i];
							if (img_height <= 600) {
								persent = arr[i];
								img_width = real_width / arr[i];
								break;
							}
						}
					}
				}
				$("#persent").val(persent);
				$('#target').css({
					width : img_width + 'px',
					height : img_height + 'px'
				});
				$("#pop-up-modal").css({
					"position" : "absolute",
					"z-index" : 11000,
					"left" : 50 + "%",
					"margin-left" : -($('#pop-up-modal').outerWidth() / 2) + "px",
					"top" : $("html").scrollTop() + "px"
				}).fadeIn();
				$(showImgDiv).val(msg);
				// 非正比例裁剪
				if (successType == 'cut01') {
					cutPic(1.5);
				} else if (successType == 'cut02') {
					cutPic(1);
				}
			}
	}else if(successType=='img'){  
		$(showImgDiv).attr("src",msg); 
		$(showImgDiv).attr("value",msg);
		$("#businessCard").val(msg);
		var img = new Image();
			img.src = msg;  
			
		if(clickId=='ii' || clickId=="headUrl1"){
            $("#queren").css("display","block");
            $(".weui_cell_ft").css("display","none");
        }
        if(clickId=='logoButton'){
            $('#saveLogo').attr('disabled',false);
        }
		$('#'+clickId).parents('.showUploadImg').hide(); 
		$(showImgDiv).parents('.showUploadImg').show(); 
		
		$(progressBar).css({'width':'0%'});
		$(progressBar).parent('div').hide(); 
		
		//显示图片裁剪框
		$(".current-pic>img").attr('src',msg); 
		$(".current-pic>img").cropper('replace', msg);
		$("#cutpic-modal").fadeIn(300);
	}else if(successType=='multi_img'){ 
		//上传的项目图片不超过6张
		var i = 0; 
		$("img[name='proPic']").each(function(){
			i++; 
		}); 
		if( i > 5){
			$(progressBar).css({'width':'0%'});
			$(progressBar).parent('div').hide();  
			
			if($(showImgDiv).children('#errorMultiImg').length < 1){ 
				$(showImgDiv).append("<div id='errorMultiImg'>上传图片不超过6张</div>");
				setTimeout(function(){
					$('#errorMultiImg').remove();
				},5000); 
			}
			return;
		} 
		$(".fb-form .fileBox i:first").attr("class","iconfont icon-xiangji1");
		var imgSpan= '';
			imgSpan+='<span><img name="proPic" value="'+msg+'" src="'+msg+'" style="border:none" />'  
			//imgSpan+='	<a class="cancelImg" onclick="cancelImgSpan(this)" ><img src="/home/images/cancel_01.png" width="25" height="25"/></a>'
			imgSpan+='</span>';
		$(showImgDiv).append(imgSpan);
		$(progressBar).css({'width':'0%'});
		$(progressBar).parent('div').hide();   
	}else if(successType=='otherFile'){   
		var fileName=msg.substr(msg.lastIndexOf("/")+1,msg.length);
		$(showImgDiv).parents('.itemContent').find('.fileCancel').css("display","inline-block");  
		$('#'+clickId).parents('.fileBtn').hide(); 
		$(showImgDiv).parents('.fileBtn').show();   
		$(showImgDiv).attr("value",msg);
		$(showImgDiv).attr("title",fileName);
		$(showImgDiv).html(fileName);
		$(progressBar).css({'width':'0%'});
		$(progressBar).parent('div').hide();
	}else if(successType == "BPFile"){  
		//BP文件上传成功后执行以下程序
		$(showImgDiv).attr("src",msg); 
		$(showImgDiv).attr("value",msg);
		$("#businessCard").val(msg);
		$(".pmgressbar-box").hide(200);
		$(".current-file a, .book-name").html(file.name).attr("title",file.name);
		$("#BpButton").parents(".item").next(".err").remove();
		setTimeout(function(){
			$(".current-file, .book-name").show();
		},300);	
	} else if(successType == "folderFile"){
		//工具文件管理上传文件
		if(json.status==true) {
			//showTips("上传成功");
			location.reload();
		}
	}
}

/***
var clickId     //上传按钮id
var fileName    //文件对应服务器（参数名字)
var url 		//上传地址
var maxFileSize //文件最大尺寸
var FileType    //文件类型
var progressBar //文件上传进度条DiV
var successType //文件处理类型判断，主要用于区分裁剪功能
var showImgDiv //文件上传后，显示在哪个DIV
var errorId //自定义参数ID
	 
***/		
	
function uploadFile(fileName,url,clickId,maxFileSize,FileType,progressBar,successType,showImgDiv,errorId){
var uploader = new plupload.Uploader({ 
	        runtimes : 'html5,flash,html4',
			browse_button : clickId, // you can pass in id...
	        url : url, 
			file_data_name:fileName,	//post  服务器文件名
	        unique_names : true,
			multi_selection: ( successType=='multi_img')?true:false , 		//判断多选图片 
	        
	        filters : {
	            max_file_size : maxFileSize,

				// Specify what files to browse for
	            mime_types: [
	                {title : " files", extensions : FileType}, //过滤文件类型
	            ]
	        },
			flash_swf_url : swf_url,
			silverlight_xap_url : xap_url, 
	 
	        // Post init events, bound after the internal events
	        init : {
	            UploadProgress: function(up, file) {
					if(up.runtime !='html4'){ 
						//新建项目特殊处理
						if(successType == 'BPFile'){
							$(".current-file").hide();
							$(progressBar).parent('div').show();
							$(progressBar).find('span').css({'width':file.percent+'%'});//进度条  
						}else{
							$(progressBar).parent('div').show();
							$(progressBar).css({'width':file.percent+'%'});//进度条  
							$('#zhengzai').show();
						}
					}
	            },
	            FilesAdded: function(up, files) {	//选择文件后
	                // Called when files are added to queue
					uploader.start();
					if(up.runtime=='html4'){  
						$(progressBar).parent('div').css({'background':'#FFF'}).append("<div id='html4Progress' class='loading'></div><div id='html4ProgressFont' style='font-size:10px;color:red'>正在上传...</div>").show();//html4的进度条  
					}
					//显示loading
					$(".fb-form .fileBox i:first").attr("class","iconfont icon-jishi loading");
	            },
				 FileUploaded: function(up, file, info) {	//单个文件上传完成后触发
					if(up.runtime=='html4'){ 
						$('#html4Progress','#html4ProgressFont').remove();  
					}
					var str = info.response;
					if(str != '' && str != null){
						var start = str.indexOf("{");
						var end = str.indexOf("}");
						if(start == -1 || end ==-1){
							showPluploadError(up,'',clickId,"上传失败",errorId)
						}else{
							var result = str.substr(start,end-start+1);
							var json =  eval("("+result+")");   
							if(json.status){ 
								showPluploadSuccess(file,json.uploadFile,successType,progressBar,showImgDiv,clickId,json); 
							}else{
								showPluploadError(up,'',clickId,json.msg,errorId);
							}
						}
					}else{
						showPluploadError(up,'',clickId,"上传失败",errorId)
					}

					if(successType != 'BPFile'){
						$(progressBar).parent('div').hide();
					}
					$('#zhengzai').hide();
					
			   },
			   Error: function(up, args) {
	                // Called when error occurs 
	                showPluploadError(up,'',clickId,args.message,errorId)
	            } 

	        }
	    });			
		//调用相机
		uploader.bind('init',function(){
			$('#camera').siblings('div').find('input').attr('accept','image/*').attr('capture','camera');
		});
		uploader.init();
} 
 
function showPluploadError(up,file,clickId,msg,errorId){
	//up.removeFile(file);
	if(errorId == null){
		alert(msg);
	}else{
		$('.'+errorId).html(msg).css({"color":"red" });
		$("."+errorId).fadeIn("slow");
		setTimeout(function(){
			$('.'+errorId).fadeOut('slow');
		},2000);
	}
} 
